﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.MenuCommand;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.MenuCommandHandler
{
    public class JLMenuListCommandHandler : IRequestHandler<JLMenuListCommand, APIResult<List<JLMenuDto>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepository;
        private readonly IMapper mapper;

        public JLMenuListCommandHandler(IBaseRepository<MenuModel> menuRepository,IMapper mapper)
        {
            this.menuRepository = menuRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<List<JLMenuDto>>> Handle(JLMenuListCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<JLMenuDto>> result = new APIResult<List<JLMenuDto>>();
            result.Code=APIEnum.查询成功;
            result.Msg=APIEnum.查询成功.ToString();
            result.data = GetTree(0);
            return Task.FromResult(result);
        }

        public List<JLMenuDto> GetTree(long parentId)
        {
            var menus=menuRepository.GetAll().Result.Where(x=>x.ParentId==parentId);
            var menudto=mapper.Map<List<JLMenuDto>>(menus);
            foreach(var menu in menudto)
            {
                menu.ChilDren=GetTree(menu.MenuId);
            }
            return menudto;
        }
    }
}
